package org.artifact.core.plugin.netty.codec;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.artifact.core.context.bytebuf.IByteBuff;
import org.artifact.core.context.bytebuf.NetworkByteBuff;
import org.artifact.core.context.packet.NetworkPacket;
import org.artifact.core.server.ServerContext;

import java.util.List;

public class NetworkDecoder extends ByteToMessageDecoder {

	static final Log log = LogFactory.get(NetworkDecoder.class);
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		int readableBytes = in.readableBytes();

		if (readableBytes < Integer.BYTES) {
			return;
		}
		
		// 记录即将开始读取的位置
		in.markReaderIndex();

		int length = in.readInt();

		// 没有内容
		if (length <= 0) {
			log.warn("0 length packet");
			ctx.close();
			return;
		}

		// 不够包长，不进行接收
		if (readableBytes < length + Integer.BYTES) {
			in.resetReaderIndex();
			return;
		}

//		IByteBuff byteBuff = new NetworkByteBuff(in);
		
		IByteBuff byteBuff = ServerContext.me().getProtocolBufferProvider().create(in);
		
		NetworkPacket packet = new NetworkPacket();
		packet.forByteBuff(byteBuff);
		out.add(packet);
	}
}
